package com.tong.torchtest;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";

    private CameraManager mCameraManager = null;
    private Camera camera;
    private boolean FlashlightEnable = false;
    private static ImageView imageButton;
    private boolean imageStatues = false;
    private String mCameraId ;

    private static int num = 0;
    private static int count = 0;

    //todo 监听手电筒状态
    private final CameraManager.TorchCallback mTorchCallback =
            new CameraManager.TorchCallback() {
                @Override
                public void onTorchModeUnavailable(String cameraId) {
                    FlashlightEnable = false;
                    if (imageStatues) {
                        imageStatues = false;
                        change();
                    }
                }

                @Override
                public void onTorchModeChanged(@NonNull String cameraId, boolean enabled) {
                    super.onTorchModeChanged(cameraId, enabled);

                    Log.d(TAG, "onTorchModeChanged: cameraId  "+cameraId+"  enabled  "+enabled+" FlashlightEnable  "+FlashlightEnable+"  imageStatues  "+ imageStatues);
                    if (!cameraId.equals(mCameraId)){
                        return;
                    }
                    if (FlashlightEnable != enabled) {
                        FlashlightEnable = enabled;
                    }
                    if (imageStatues != enabled) {
                        imageStatues = enabled;
                        change();
                    }
                    Log.d(TAG, "onTorchModeChanged: " + enabled + "  FlashlightEnable:"
                            + FlashlightEnable + "    imageStatues:" + imageStatues+"   num="+num++);
                }
            };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化
        initView();
        //获得mCameraManager对象
        this.mCameraManager = (CameraManager) getApplication().getSystemService(Context.CAMERA_SERVICE);
        //获得CameraID，注册手电筒回调
        tryInitCamera();
        //默认开启程序，打开手电筒
        openFlashlight();
        imageButton.setImageResource(R.drawable.opening);
        Log.d(TAG, "onCreate: imageStatues  "+imageStatues);
    }

    private void initView() {
        imageButton = findViewById(R.id.open_button);
        imageButton.setOnClickListener(this);
    }

    //获得CameraID，注册手电筒回调
    private void tryInitCamera() {
        try {
            mCameraId = getCameraId();
            Log.d(TAG, "tryInitCamera: mCameraId  "+mCameraId);
        } catch (Throwable e) {
            Log.e(TAG, "Couldn't initialize.", e);
            return;
        }
        if (mCameraId != null) {
            mCameraManager.registerTorchCallback(mTorchCallback, null);
        }
    }

    private String getCameraId() throws CameraAccessException {
        String[] ids = mCameraManager.getCameraIdList();
        for (String id : ids) {
            CameraCharacteristics c = mCameraManager.getCameraCharacteristics(id);
            Boolean flashAvailable = c.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
            Integer lensFacing = c.get(CameraCharacteristics.LENS_FACING);
            if (flashAvailable != null && flashAvailable
                    && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_BACK) {
                return id;
            }
        }
        return null;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Log.d(TAG, "onBackPressed: ");

        back = true;

    }


    private boolean back = false;

    @Override
    protected void onStop() {
        Log.d(TAG, "onStop: ");
        if (back){
            closeFlashlight();
            back = !back;
        }

        super.onStop();
    }

    @Override
    protected void onRestart() {
        Log.d(TAG, "onRestart: ");
        super.onRestart();
    }


    @Override
    protected void onPostResume() {
        Log.d(TAG, "onPostResume: ");
        super.onPostResume();
    }

    @Override
    public void onClick(View v) {
        if (imageStatues) {
            closeFlashlight();
            imageButton.setImageResource(R.drawable.openbutton);
        } else {
            openFlashlight();
            imageButton.setImageResource(R.drawable.opening);
        }
        imageStatues = !imageStatues;
    }

    private void change() {
        if (imageStatues) {
            imageButton.setImageResource(R.drawable.opening);
        } else {
            imageButton.setImageResource(R.drawable.openbutton);
        }

    }


    private void openFlashlight() {

        try {
            if (mCameraManager != null) {
                mCameraManager.setTorchMode(mCameraId, true);
            } else {
                camera = Camera.open();
                Camera.Parameters parameters = camera.getParameters();
                parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                camera.setParameters(parameters);
                camera.startPreview();
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }


    private void closeFlashlight() {
        Log.d(TAG, "closeFlashlight: ");
        try {
            if (mCameraManager != null) {
                mCameraManager.setTorchMode(mCameraId, false);
            } else {
                if (camera == null) {
                    camera = Camera.open();
                }
                camera.stopPreview();
                camera.release();
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {

        Log.d(TAG, "onDestroy: mCameraManager"+mCameraManager);

        if (mCameraManager != null && mTorchCallback != null) {
            Log.d(TAG, "onDestroy: unregister");
            mCameraManager.unregisterTorchCallback(mTorchCallback);
        }

        super.onDestroy();

        Log.d(TAG, "onDestroy: 2");

    }

}
